3.7 form表单编码格式
from表单发送POST请求,请求体中支持的数据格式有三种:
• text/plain
•appliction/x-www-from-urlencoded
•multipart/form-data
使用form表单时,可以修改enctype的值为这三个中的一个,默认是urlencoded纯文件。
如果请求体数据编码为text/plain
•请求头中:Content-Type:text/plain
•请求体的数据格式为:b’name=wei\r\nage=40\r\n’
•此时无法使用request.POST 获取请求体数据,只能使用 request.body
Urlencoded 请求体数据按照URL上的查询参数的格式编码
•请求头中:Content-Type:application/x-www-form-urlencoded
•请求体的数据格式为:b’name=wei&age=40’
•此时会选择使用request.POST获取请求体数据,一般不会使用request.body 手动解析数据
form-data:这种格式主要用于上传文件的需求,但是也可以上传非文件数据
•请求体中:Content-Type:multipart/form-data:boundary=----webkifFormBoundaryx8xYcBFZbnQSRDi0 name=”name”\r\n\r\nweiu\r\n------WebkifFormBoundda”yx8xYcBFZBnQSRDi0\r\rContent-Dispostion:form-data;name=”age”\r\n\r\n20\r\n----WebkitFormBoundaryx8xYcBFBnQSRDi0--\r\n”
•此时,使用ruquest.POST获取非文件数据,使用request.FILES获取文件数据
总结:
在Django中,不论何种格式的请求体数据,都可以使用request.body来获取,但这种方式拿到的是一个字节字符串,包含HTTP的原始数据。大多数情况下,我们不会直接使用request.body来获取请求体数据。针对不同格式的请求体数据,有专门的方法来提取数据。
html6
< html >
< head >
< meta charset="UTF-8" >
< meta http-equiv="X-UA-Compatible" content="ie=edge" >
< title > Document < /title >
< /head >
< body >
< form action="http://127.0.0.1:8000/app03/test6" method="post" enctype="text/plain" >
< !-- enctype有三种格式,默认是enctype=application/x-www-form-urlencoded-- >
< P > 姓名: < input type="text" name="name" > < /P >
< P > 年龄: < input type="text" name="age" > < /P >
< input type="submit" value="提交" >
< /form >
< /body >
< /html >
返回:
b'name=wei\r\nage=40\r\n'
< QueryDict: {} >
None
[19/May/2024 09:24:58] "POST /app03/test6 HTTP/1.1" 200 10